﻿using System;
using System.IO;
using System.Text;
using System.Web;

namespace CommonUtils
{
    /// <summary>
    /// 编码解码工具
    /// </summary>
    public static class EncodeUtil
    {
        /// <summary>
        /// UrlEncode
        /// </summary>
        public static string UrlEncode(this string text)
        => HttpUtility.UrlEncode(text);

        /// <summary>
        /// UrlDecode
        /// </summary>
        public static string UrlDecode(this string text)
        => HttpUtility.UrlDecode(text);

        /// <summary>
        /// base64编码
        /// </summary>
        public static string Base64Encode(this byte[] bytes)
        => Convert.ToBase64String(bytes);

        /// <summary>
        /// base64编码
        /// </summary>
        public static string Base64Encode(this Stream stream)
        => stream.ToBytes().Base64Encode();

        /// <summary>
        /// base64编码
        /// </summary>
        public static string Base64Encode(this string text, Encoding encoding = null)
        => text.Encode(encoding).Base64Encode();

        /// <summary>
        /// 将base64整理为C#可用格式
        /// </summary>
        public static string Base64Sort(this string base64)
        => base64.Replace(' ', '+');

        /// <summary>
        /// base64解码
        /// </summary>
        public static byte[] Base64Decode(this string base64)
        {
            try
            {
                return Convert.FromBase64String(base64);
            }
            catch (Exception ex)
            {
                return ex.Message.ToBytes();
            }
        }

        /// <summary>
        /// base64解码
        /// </summary>
        public static string Base64DecodeString(this string base64, Encoding encoding = null)
        => base64.Base64Decode().Decode(encoding);

        public static Encoding GB2312 => TextEncoding.GB2312;
        public static Encoding GBK => TextEncoding.GBK;
        public static Encoding UTF8 => TextEncoding.UTF8;
        public static Encoding UTF8NoBom => TextEncoding.UTF8NoBom;
    }
}
